﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using KingRoad.EPM.DeviceEntity.Model;
using KingRoad.EPM.Web.Areas.Device.Models;
using DotNet.Model.MyEntity;
using DotNet.Service;
using DotNet.Utilities;
using System.Data;
using System.Text;
using KingRoad.EPM.DeviceBLL.UIRules;
using Unis.Framework.Core.Infrastructure;
using Unis.Framework.Core.Utility;
using KingRoad.EPM.DeviceDAL.BllRoadwayService;
using KingRoad.EPM.DeviceDAL;
using NPOI.SS.Util;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using BorderStyle = NPOI.SS.UserModel.BorderStyle;
using VerticalAlignment = NPOI.SS.UserModel.VerticalAlignment;
using Novacode;
using System.IO;
using System.Text.RegularExpressions;


namespace KingRoad.EPM.Web.Areas.Device.Controllers
{
    public class BaseController : Controller
    {
        /// <summary>
        /// 车道信息UIRule
        /// </summary>
        public BllRoadwayUIRule BllRoadwayUIRule = new BllRoadwayUIRule(new BllRoadwayService());

        /// <summary>
        /// 仪表信息UIRule
        /// </summary>
        public BllMeterUIRule BllMeterUIRule = new BllMeterUIRule(new BllMeterService());

        /// <summary>
        /// 实时数据信息UIRule
        /// </summary>
        public BllVehicleflowUIRule BllVehicleflowUIRule = new BllVehicleflowUIRule(new BllVehicleflowService());


        /// <summary>
        /// 获取组织机构
        /// </summary>
        /// <returns></returns>
        public JsonResult GetOrgJson()
        {
            DotNet.Utilities.BaseUserInfo info = UserService.CurrUserInfo;
            string url = Request.QueryString["url"];
            List<Base_Org> list = ServiceManager.Instance.OrganizeService.GetOrgChild(info.DepartmentId.ToString()) as List<Base_Org>;
            List<treeNodes> treenodes = new List<treeNodes>();
            foreach (Base_Org tInfo in list)
            {
                if (tInfo.DeletionStateCode!=1)
                {
                    
                
                treeNodes node = new treeNodes();
                node.id = tInfo.Id.ToString();
                node.pId = tInfo.ParentId.ToString();
                node.name = tInfo.FullName;
                 if (tInfo.Bank == "Company")
                     node.iconSkin = "iCandyCompany";
                 if (tInfo.Bank == "Department")
                     node.iconSkin = "iCandyDuty";
                 node.target = "ajax";
                 node.url = url + "?placId=" + tInfo.Id + "&Code=" + tInfo.Code;// HttpUtility.UrlEncode(info.Name, Encoding.GetEncoding("UTF-8")); 
                 treenodes.Add(node);
                }

            }
            return Json(treenodes, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 设置excel样式
        /// </summary>
        /// <param name="book">工作簿</param>
        /// <param name="align">水平对齐方式（center、left、right）</param>
        /// <param name="border">是否有边框</param>
        /// <param name="size">字体大小</param>
        /// <param name="weight">字体粗细</param>
        /// <returns></returns>
        public ICellStyle Getcellstyle(IWorkbook book, string align = "center", bool border = true, short size = 10, short weight = 100)
        {
            ICellStyle style = book.CreateCellStyle();
            //垂直对齐
            style.VerticalAlignment = VerticalAlignment.Center;
            //自动换行
            style.WrapText = true;
            //水平对齐
            switch (align)
            {
                case "center":
                    style.Alignment = HorizontalAlignment.Center;
                    break;
                case "left":
                    style.Alignment = HorizontalAlignment.Left;
                    break;
                case "right":
                    style.Alignment = HorizontalAlignment.Right;
                    break;
                default:
                    style.Alignment = HorizontalAlignment.Center;
                    break;
            }
            //字体
            IFont font = book.CreateFont();
            font.FontHeightInPoints = size;
            font.Boldweight = weight;
            style.SetFont(font);
            if (border)
            {
                style.BorderTop = BorderStyle.Thin;
                style.BorderBottom = BorderStyle.Thin;
                style.BorderLeft = BorderStyle.Thin;
                style.BorderRight = BorderStyle.Thin;
            }
            return style;
        }
        /// <summary>
        /// 创建单元格
        /// </summary>
        /// <param name="row">行实体</param>
        /// <param name="index">列数</param>
        /// <param name="style">单元格样式</param>
        /// <param name="value">单元格值</param>
        public void CreateCell(IRow row, int column, ICellStyle style, string value)
        {
            ICell cell = row.CreateCell(column);
            cell.CellStyle = style;
            cell.SetCellValue(value);
        }
        /// <summary>
        /// 根据Excel列类型获取列的值
        /// </summary>
        /// <param name="cell">单元格</param>
        /// <returns></returns>
        public string GetCellValue(ICell cell)
        {
            if (cell == null)
                return string.Empty;
            switch (cell.CellType)
            {
                case CellType.Blank:
                    return string.Empty;
                case CellType.Boolean:
                    return cell.BooleanCellValue.ToString();
                case CellType.Error:
                    return cell.ErrorCellValue.ToString();
                case CellType.Numeric:
                    if (NPOI.SS.UserModel.DateUtil.IsCellDateFormatted(cell))
                    {
                        return cell.DateCellValue.ToString();
                    }
                    else
                    {
                        return cell.ToString();
                    }
                case CellType.Unknown:
                default:
                    return cell.ToString();
                case CellType.String:
                    return cell.StringCellValue;
                case CellType.Formula:
                    try
                    {
                        HSSFFormulaEvaluator e = new HSSFFormulaEvaluator(cell.Sheet.Workbook);
                        e.EvaluateInCell(cell);
                        return cell.ToString();
                    }
                    catch
                    {
                        return cell.NumericCellValue.ToString();
                    }
            }
        }
        /// <summary>
        /// 根据模板中标签导出word文档
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="fileName"></param>
        /// <param name="t"></param>
        /// <returns></returns>
        public FileStreamResult ExportToWord<T>(string fileName, T t)
        {
            string path = Server.MapPath("~/Areas/PersonnelLog/Upload/" + fileName);
            string savePath = Server.MapPath("~/Areas/PersonnelLog/Upload/Temp/" + Guid.NewGuid().ToString() + fileName);
            using (DocX docx = DocX.Load(path))
            {
                var rex = new Regex("[0-9]+?");
                docx.Bookmarks.ForEach(f =>
                {
                    var bookMarkName = f.Name;
                    if (rex.IsMatch(bookMarkName))
                    {
                        bookMarkName = f.Name.Substring(0, f.Name.Length - 1);
                    }

                    if (t.ContainProperty(bookMarkName))
                    {
                        var obj = Reflection.GetProperty(t, bookMarkName);
                        var value = obj ?? "";
                        var propertyType = value.GetType().FullName;
                        if (propertyType == "System.DateTime")
                            f.SetText(Convert.ToDateTime(value).ToString("yyyy年MM月dd日"));
                        else
                            f.SetText(value.ToString());
                    }
                });
                docx.SaveAs(savePath);
            }
            fileName = HttpUtility.UrlEncode(fileName, Encoding.GetEncoding("UTF-8"));
            FileStream file = new FileStream(savePath, FileMode.Open);
            return File(file, "application/vnd.ms-word", fileName);
        }
    }
}
